const app = getApp();
import config from '../../../utils/config.js';
import {Request} from '../../../utils/request.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    
    showLogin: false, //登陆弹出框
    loading: false,

    activity_id: 0,
    congratulations: [],
    rewardPrize: {},

    showModal: false, // 显示modal弹窗
    single: true, // true 只显示一个按钮，如果想显示两个改为false即可

    score: 0, //总积分
    need: 0, //需要花费的积分
    activity_prize: [],
    is_play: false, //是否在运动中，避免重复启动bug
    available_num: 0, //可用抽奖的次数，可自定义设置或者接口返回
    start_position: 0, //转动开始时首次点亮的位置，可自定义设置
    base_circle_num: 5, //基本圈数，就是在转到（最后一圈）结束圈之前必须转够几圈 ，可自定义设置
    low_circle_num: 4, //在第几圈开始进入减速圈（必须小于等于基本圈数），可自定义设置
    use_speed: 60, //当前速度，与正常转速值相等
    nor_speed: 60, //正常转速，在减速圈之前的转速，可自定义设置
    low_speed: 120, //减速转速，在减速圈的转速，可自定义设置
    end_speed: 250, //最后转速，在结束圈的转速，可自定义设置
    random_number: 0, //中奖索引，也是随机数，也是结束圈停止的位置，这个值采用系统随机或者接口返回
    change_num: 0, //变化计数，0开始，比如实例有12个奖项，基本是6圈，那么到结束这个值=6*12+random_number；同样change_num/12整除表示走过一整圈
    result_val: "未中奖", //存放奖项容器，可自定义设置
    joinData: {}
  },


  loadingSuccess() {
    this.setData({
      loading: true,
    })
  },

  //启动
  start: function () {
    var that = this;
    //是否用完可用抽奖次数
    //console.log(that.data.available_num);

    if (!(that.data.available_num > 0 || that.data.need <= that.data.score)) {
      wx.showToast({
        title: "您积分或免费次数已用完",
        icon: 'none',
        duration: 1500
      });
      return false;
    }
    //阻止运动中重复点击
    if (!that.data.is_play) {

      //重置参数
      that.reset();

      //设置标识在运动中
      let authorization = app.globalData.authorization;
      if (authorization != null) {
        that.setData({
          is_play: true
        });
        //运动函数
        setTimeout(that.dong, that.data.use_speed);
      }


      //生成随机奖项索引(0-that.data.Jack_pots.length)之间 || 或者后台返回这个获奖内容
      //方式1 后台

      that.join();

      //方式2 随机
      // that.setData({ random_number: Math.floor(Math.random() * that.data.activity_prize.length) });
      //console.log(that.data.random_number);


    };

  },

  //运动函数
  dong: function () {
    var that = this;

    //点亮
    let activity_prize = that.data.activity_prize;
    for (var j = 0; j < activity_prize.length; j++) {
      if (j == that.data.change_num % activity_prize.length) {
        activity_prize[j].selected = true;
      } else {
        activity_prize[j].selected = false;
      }
    }

    that.setData({
      activity_prize: activity_prize,
      change_num: that.data.change_num + 1,
    });

    //继续运动
    if (that.data.change_num > that.data.base_circle_num * that.data.activity_prize.length + that.data.random_number) { //已经到达结束位置
      //提示中奖，
      // console.log(that.data.Jack_pots_val[that.data.random_number])
      that.setData({
        result_img: that.data.activity_prize[that.data.random_number].cover,
        result_val: that.data.activity_prize[that.data.random_number].name,
        showModal: true
      })
      // wx.showModal({
      //   showCancel: false,
      //   title: '提示',
      //   content: that.data.activity_prize[that.data.random_number].name,
      // })
      //code

      //运动结束设置可用抽奖的次数和激活状态设置可用
      that.endset();


    } else { //运动
      //console.log(that.data.change_num)
      if (that.data.change_num / that.data.activity_prize.length + 1 < that.data.low_circle_num) { //正常转速
        //console.log("正常转速")
        that.data.use_speed = that.data.nor_speed
      } else if (that.data.change_num / that.data.activity_prize.length + 1 >= that.data.low_circle_num && that.data.change_num / that.data.activity_prize.length + 1 <= that.data.base_circle_num + 1) { //减速圈
        //console.log("减速圈")
        that.data.use_speed = that.data.low_speed
      } else if (that.data.change_num / that.data.activity_prize.length + 1 > that.data.base_circle_num + 1) { //结束圈
        //console.log("结束圈")
        that.data.use_speed = that.data.end_speed
      }
      setTimeout(that.dong, that.data.use_speed);
    }

  },

  //运动结束设置可用抽奖的次数和激活状态设置可用
  endset: function () {
    var that = this;
    //是否在运动中，避免重复启动bug
    that.setData({
      is_play: false
    })
    //可用抽奖的次数，可自定义设置
    if (that.data.available_num > 0) {
      that.setData({
        available_num: that.data.available_num - 1
      });
    } else { //用的积分
      that.setData({
        score: that.data.score - that.data.need
      });
    }
  },

  //重置参数
  reset: function () {
    var that = this;
    //转动开始时首次点亮的位置，可自定义设置
    that.setData({
      start_position: 0
    });
    //当前速度，与正常转速值相等
    that.setData({
      use_speed: that.data.nor_speed
    });
    //中奖索引，也是随机数，也是结束圈停止的位置，这个值采用系统随机或者接口返回
    that.setData({
      random_number: 0
    });
    //变化计数，0开始，必须实例有12个奖项，基本是6圈，那么到结束这个值=6*12+random_number；同样change_num/12整除表示走过一整圈
    that.setData({
      change_num: 0
    });

  },

  // 弹窗确认
  modalConfirm: function() {
    if(this.data.joinData.type != 'thanks') {
      wx.navigateTo({
        url: '/pages/activity/win/win',
      })
    }
  },

  loginSuccess: function() {
    that.postUserInfo();
  },
  loginDialog: function(e) {
    this.setData({
      showLogin: e.detail.flag
    })
  },

  join: function () {
    let that = this;
    if (!app.checkLogin()) {
      return;
    }

    let param = {
      url: 'activity/join',
      method: 'POST',
      data: {
        activity_id: that.data.activity_id,
      }
    }

    Request(param).then(function (res) {
      let prize = that.data.activity_prize;
      prize.forEach(function (item, index) {
        if (item.id == res.data.id) {
          that.setData({
            random_number: index,
          })
          return;
        }
      });
      that.setData({
        joinData: res.data
      });
      if (res.data.type == 'score') {
        that.setData({
          score: parseInt(that.data.score) + parseInt(res.data.type_value),
        })
      }

    });

  },

  //加载活动数据
  postActivity: function () {
    let that = this;
    let getAnimationTime = config.ANIMATIONTIME;
    let start = Date.parse(new Date());

    let param = {
      url: 'activity/get',
      method: 'POST',
      data: {}
    }

    Request(param).then(function (res) {
      that.setData({
        activity_prize: res.data.prize.filter(function (item) {
          item.selected = false;
          item.cover = item.cover;
          item.name = (item.type == 'score' ? item.score + ' ' : (item.type == 'money' ? item.money + '元 ' : '')) + item.name;
          return item;
        }),
        activity_id: res.data.id
      })

      that.congratulations(res.data.id);
    });


  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.postActivity();
    that.postUserInfo();
  },


  /***
   * 获取用户信息
   */
  postUserInfo: function () {

    let that = this

    let authorization = app.globalData.authorization;
    if (authorization == null) {
      return;
    }

    let param = {
      url: 'activity/userInfo',
      method: 'POST',
      data: {}
    }
    Request(param).then(function (res) {
      that.setData({
        score: res.data.score,
        need: res.data.cost_scroe,
        available_num: res.data.free_count,
      });

    });

  },



  congratulations: function (activity_id) {
    let that = this;
    if (!app.checkLogin()) {
      return;
    }
    let param = {
      url: 'activity/congratulations',
      method: 'POST',
      data: {
        activity_id: activity_id
      }
    }
    Request(param).then(function (res) {
      that.setData({
        congratulations: res.data
      })
    });
  },

  //中奖纪录
  goActivityWin: function () {
    if (!app.checkLogin()) {
      return;
    }
    wx.navigateTo({
      url: '/pages/activity/win/win',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return app.shareAppMessage();
  }
})